package project.dade.cn.bst.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;

import java.util.List;

import cn.bingoogolapple.androidcommon.adapter.BGAOnRVItemClickListener;
import cn.bingoogolapple.androidcommon.adapter.BGARecyclerViewAdapter;
import cn.bingoogolapple.androidcommon.adapter.BGAViewHolderHelper;
import project.dade.cn.bst.R;
import project.dade.cn.bst.base.ZJPBaseBarActivity;
import project.dade.cn.bst.utils.Divider;
import project.dade.cn.bst.utils.LocationUtil;
import project.dade.cn.bst.utils.LogUtil;
import project.dade.cn.bst.utils.PermissionUtil;
import project.dade.cn.bst.utils.SimpleOnCameraChangeListener;
import project.dade.cn.bst.utils.SimpleOnMarkerDragListener;


public class ChooseAddressActivity extends ZJPBaseBarActivity implements AMapLocationListener, BGAOnRVItemClickListener {
    private static final int REQUEST_CODE_LOCATION = 1;
    public static int RESULT_CODE = 1201;
    private Activity mActivity;
    private AMap mAMap;
    private MapView mMapMv;
    private Marker mMarker;
    private LatLng mLatLng;
    private RecyclerView mContentRv;
    private LocationAdapter mLocationAdapter;
    private String cityCode;
    private String type="";
    private String mark="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chooseaddress);
        mMapMv = (MapView) findViewById(R.id.mv_choose_location);
        mContentRv = (RecyclerView) findViewById(R.id.rv_choose_location);
        mMapMv.onCreate(savedInstanceState);
        mActivity = ChooseAddressActivity.this;
        type=getIntent().getStringExtra("type");
        mark=getIntent().getStringExtra("mark");
        LogUtil.i(TAG, "跳转界面："+type);
        mContentRv.setLayoutManager(new LinearLayoutManager(this));
        mContentRv.addItemDecoration(new Divider(this));
        mLocationAdapter = new LocationAdapter(mContentRv);
        mLocationAdapter.setOnRVItemClickListener(this);
        mContentRv.setAdapter(mLocationAdapter);
        setUpMap();
    }

    private void setUpMap() {
        if (mAMap != null) {
            return;
        }
        mAMap = mMapMv.getMap();
        mAMap.getUiSettings().setMyLocationButtonEnabled(true);
        mAMap.setMyLocationEnabled(true);
        mAMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                mLatLng = latLng;
                refreshMap();
            }
        });
        mAMap.setOnMarkerDragListener(new SimpleOnMarkerDragListener() {
            @Override
            public void onMarkerDragStart(Marker marker) {
                marker.hideInfoWindow();
            }

            @Override
            public void onMarkerDragEnd(Marker marker) {
                mLatLng = marker.getPosition();
                searchAddress();
            }
        });
        mAMap.setOnCameraChangeListener(new SimpleOnCameraChangeListener() {
            @Override
            public void onCameraChangeFinish(CameraPosition cameraPosition) {
                mLatLng = cameraPosition.target;
                searchAddress();
            }
        });
        mAMap.setLocationSource(new LocationSource() {
            @Override
            public void activate(OnLocationChangedListener onLocationChangedListener) {
                requestLocation();
            }

            @Override
            public void deactivate() {
            }
        });



    }
    private void requestLocation() {

        PermissionUtil.request(this, REQUEST_CODE_LOCATION, new PermissionUtil.Delegate() {
            @Override
            public void onPermissionGranted() {
                LocationUtil.requestLocation(mActivity,true, ChooseAddressActivity.this);
            }

            @Override
            public void onPermissionDenied() {

            }
        }, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        PermissionUtil.request(this, REQUEST_CODE_LOCATION, new PermissionUtil.Delegate() {
            @Override
            public void onPermissionGranted() {
                LocationUtil.requestLocation(mActivity, true, ChooseAddressActivity.this);
            }

            @Override
            public void onPermissionDenied() {
                Toast.makeText(mActivity, "Some Permission is Denied", Toast.LENGTH_SHORT).show();
            }
        }, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_LOCATION:
                PermissionUtil.result(permissions, grantResults, new PermissionUtil.Delegate() {
                    @Override
                    public void onPermissionGranted() {
                        LocationUtil.requestLocation(mActivity,true,ChooseAddressActivity.this);
                    }

                    @Override
                    public void onPermissionDenied() {
                        Toast.makeText(mActivity,"Some Permission is Denied",Toast.LENGTH_SHORT).show();
                    }
                });
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        mMapMv.onResume();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        mMapMv.onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }


    @Override
    protected void onPause() {
        mMapMv.onPause();
        LocationUtil.stopLocation();
        super.onPause();
    }


    @Override
    protected void onDestroy() {
        mMapMv.onDestroy();
        LocationUtil.onDestroy();
        super.onDestroy();
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            this.finish();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    private void searchAddress() {
        String qType = "商务住宅";
        final PoiItem mCurrentPoiItem = new PoiItem(null, new LatLonPoint(mLatLng.latitude, mLatLng.longitude), "", null);
        PoiSearch.Query query = new PoiSearch.Query("*", qType, cityCode);
        query.setPageSize(50);
        query.setPageNum(0);
        PoiSearch poiSearch = new PoiSearch(mActivity, query);
        poiSearch.setBound(new PoiSearch.SearchBound(new LatLonPoint(mLatLng.latitude, mLatLng.longitude), 1000));
        poiSearch.setOnPoiSearchListener(new PoiSearch.OnPoiSearchListener() {
            @Override
            public void onPoiSearched(PoiResult poiResult, int i) {
                if(i==0){
                    List<PoiItem> poiItems = poiResult.getPois();
                    PoiItem poiItem = poiItems.get(0);
                    refreshMarker(TextUtils.isEmpty(poiItem.getPoiId()) ? poiItem.getTitle() : poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getTitle());
                    mLocationAdapter.setDatas(poiItems);
                }else if(i==200){

                }
            }
        });
        poiSearch.searchPOIAsyn();
    }

    //
    private void refreshMap() {
        mAMap.animateCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(mLatLng, 18, 0, 0)), 700, null);
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (aMapLocation != null && aMapLocation.getErrorCode() == 0) {
            mLatLng = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
            cityCode = 0512+"";
            LogUtil.i(TAG, "图片地址：" + cityCode);
            mAMap.animateCamera(new CameraUpdateFactory().newLatLngZoom(mLatLng, 18));
            if (mMarker == null) {
                mMarker = mAMap.addMarker(new MarkerOptions().position(mLatLng).icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.pin_normal))).zIndex(1));
            } else {
                mMarker.setPosition(mLatLng);
            }
        }
        refreshMap();
    }

    private void refreshMarker(String address) {
        initMarker();
        mMarker.setPosition(mLatLng);
        if (mMarker.isInfoWindowShown()) {
            mMarker.hideInfoWindow();
        }
        mMarker.showInfoWindow();
    }

    private void initMarker() {
        if (mMarker == null) {
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(mLatLng);
            markerOptions.draggable(true);
            markerOptions.icon(BitmapDescriptorFactory.fromResource(R.mipmap.pin_normal));
            mMarker = mAMap.addMarker(markerOptions);
        }
    }

    @Override
    public void onRVItemClick(ViewGroup viewGroup, View view, int position) {
        if(type.equals("1")){
            Intent mIntent = new Intent();
            Bundle mBundle = new Bundle();
            mBundle.putString("address",  getAddress(mLocationAdapter.getItem(position)));
            mBundle.putString("mark",mark);
            mIntent.putExtra("tempAddress", mBundle);
            ChooseAddressActivity.this.setResult(AddaddressActivity.RESULT_CODE, mIntent);
            ChooseAddressActivity.this.finish();

        }else if(type.equals("2")){
            Intent mIntent = new Intent();
            Bundle mBundle = new Bundle();
            mBundle.putString("address",  getAddress(mLocationAdapter.getItem(position)));
            mBundle.putString("mark",mark);
            mIntent.putExtra("tempAddress", mBundle);
            ChooseAddressActivity.this.setResult(AddCaraddtressActivity.RESULT_CODE, mIntent);
            ChooseAddressActivity.this.finish();

        }else {
            Intent mIntent = new Intent();
            Bundle mBundle = new Bundle();
            mBundle.putString("address",  getAddress(mLocationAdapter.getItem(position)));
            mBundle.putString("mark",mark);
            mIntent.putExtra("tempAddress", mBundle);
            ChooseAddressActivity.this.setResult(AddaddressActivity.RESULT_CODE, mIntent);
            ChooseAddressActivity.this.finish();
        }
    }

    public class LocationAdapter extends BGARecyclerViewAdapter<PoiItem> {

        public LocationAdapter(RecyclerView recyclerView) {
            super(recyclerView, R.layout.item_title_desc);
        }


        @Override
        protected void fillData(BGAViewHolderHelper helper, int position, PoiItem model) {
            if (position == 0) {
                helper.setText(R.id.tv_item_title_desc_title, "[当前位置]" + model.getTitle());
            } else {
                helper.setText(R.id.tv_item_title_desc_title, model.getTitle());
            }
            helper.setText(R.id.tv_item_title_desc_desc, getAddress(model));
        }

        }
    public static String getAddress(PoiItem poiItem) {
        return TextUtils.isEmpty(poiItem.getPoiId()) ? poiItem.getTitle() : poiItem.getProvinceName() + poiItem.getCityName() + poiItem.getAdName() + poiItem.getSnippet();
    }

}